/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Interfaces;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JOptionPane;
import lemar.entidad.Estante;
import lemar.ConexionHibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author Gu5Riv
 */
public class AgregarEstante extends javax.swing.JPanel {

     //Atributos para el uso de Hibernate
    private static SessionFactory sessionFactory = null;
    /**
     * Creates new form AgregarEstante
     */
    public AgregarEstante() {
        initComponents();
        
        txtCodEstante.setToolTipText("Ingrese el código del estante");
        txtUbicacionBodega.setToolTipText("Ingrese la ubicación en bodega");
        txtNumNiveles.setToolTipText("Ingrese el número de niveles");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btnIngresarEstante = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtCodEstante = new javax.swing.JTextField();
        txtUbicacionBodega = new javax.swing.JTextField();
        txtNumNiveles = new javax.swing.JTextField();

        setBackground(new java.awt.Color(255, 255, 255));
        setMaximumSize(new java.awt.Dimension(740, 430));
        setMinimumSize(new java.awt.Dimension(740, 430));
        setName(""); // NOI18N
        setPreferredSize(new java.awt.Dimension(740, 430));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Agregar Nuevo Estante");

        btnIngresarEstante.setText("Ingresar");
        btnIngresarEstante.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarEstanteActionPerformed(evt);
            }
        });

        jButton2.setText("Limpiar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Código del Estante");

        jLabel3.setText("Ubicación en Bodega");

        jLabel4.setText("Número de Niveles");

        txtNumNiveles.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNumNivelesKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(582, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnIngresarEstante)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(222, 222, 222)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(txtCodEstante, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(txtNumNiveles, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(txtUbicacionBodega, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(0, 220, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(276, 276, 276)
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(59, 59, 59)
                .addComponent(jLabel1)
                .addGap(90, 90, 90)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtCodEstante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtUbicacionBodega, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtNumNiveles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 115, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnIngresarEstante)
                    .addComponent(jButton2))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnIngresarEstanteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarEstanteActionPerformed
        // TODO add your handling code here:
        
        //Variables que contendran los valores de los campos de texto
        String codigo = "";
        String ubicacion = "";
        String numniveles = "";
        
        //Variable que maneja la respuesta del JOptionPane
        int conf;
        
        //Extrayendo la informacion de los campos de texto
        codigo = txtCodEstante.getText();
        ubicacion = txtUbicacionBodega.getText();
        numniveles = txtNumNiveles.getText();
        
        int nNiveles;
        
        //Validaciones
        if(!(codigo.isEmpty() || ubicacion.isEmpty() || numniveles.isEmpty())) { //Si no esta vacio algun campo           
                    //Chunche de Hibernate (Inicio de sesion de hibernate)
            Session session = null;
            nNiveles = Integer.parseInt(numniveles);
            try{
                try{
                    //Conexion a la BD
                    sessionFactory = ConexionHibernate.getSessionFactory();
                    //Apertura de la sesion
                    session = sessionFactory.openSession();
                    Transaction tx = session.beginTransaction();

                    //Creando el objeto Proveedor 
                    Estante estante = new Estante();
                    //Ingresando la informacion del proveedor al 
                    //objeto Proveedor
                    estante.setCodigoEstante(codigo);
                    estante.setUbicacion(ubicacion);
                    estante.setNumeroNiveles(nNiveles);
                   

                    //Mensaje de pregunta si quiere guardar los datos proporcionados 
                    conf=JOptionPane.showConfirmDialog(null,"¿Esta seguro de ingresar esos datos?","Confirmación",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                    
                    if(conf == JOptionPane.YES_OPTION){//Si la opcion fue SI
                        //Guardando el objeto en la base de datos
                        session.save(estante);
                        tx.commit();
                        //Mensaje de confirmacion de insercion Exitosa
                        JOptionPane.showMessageDialog(null,"Registro guardado exitosamente","Información",JOptionPane.INFORMATION_MESSAGE);                        
                    }     
                }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            } finally {
                //Finalizacion de la sesion de hibernate
                session.close();
        }
      }
        else {//Si hay campos vacios, mensaje de error
            JOptionPane.showMessageDialog(null,"Error, no pueden haber campos vacios","Error en los datos",JOptionPane.ERROR_MESSAGE);
        } 
    }//GEN-LAST:event_btnIngresarEstanteActionPerformed

    private void txtNumNivelesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumNivelesKeyTyped
        // SOLO NUMEROS
        char c;
        //capturar el caracter digitado
        c=evt.getKeyChar();
        if(c<'0'|| c>'9')
        {
        evt.consume();//ignora el caracter digitado 
        }
    }//GEN-LAST:event_txtNumNivelesKeyTyped

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        //Se borran los datos de los campos de texto
        txtCodEstante.setText("");
        txtUbicacionBodega.setText("");
        txtNumNiveles.setText("");
    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnIngresarEstante;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField txtCodEstante;
    private javax.swing.JTextField txtNumNiveles;
    private javax.swing.JTextField txtUbicacionBodega;
    // End of variables declaration//GEN-END:variables
}
